package com.yunxi.core.util;

import org.apache.commons.beanutils.*;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.yunxi.core.web.DateFormat;
import javax.sql.rowset.serial.SerialException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 *
 */
public class BeanTools
{
    private static final Log logger = LogFactory.getLog(BeanTools.class);
    private static DateFormat dateFormat = new DateFormat();



	/*
	 * bean2map
	 */
	public static Map bean2map(Object bean)
	{
		Map map = null;
		try
		{
			map = PropertyUtils.describe(trim(bean));
		} catch (IllegalAccessException e)
		{
			e.printStackTrace();
		} catch (InvocationTargetException e)
		{
			e.printStackTrace();
		} catch (NoSuchMethodException e)
		{
			e.printStackTrace();
		}
		return map;
	}

	public static Object map2bean(Map map, Object o)
	{
		Iterator iterMap = map.entrySet().iterator();
		while (iterMap.hasNext())
		{
			Map.Entry entry = (Map.Entry) iterMap.next();
			try
			{
				BeanUtils.setProperty(o, (String) entry.getKey(), entry
						.getValue());
			} catch (IllegalAccessException e)
			{
				// TODO 自动生成 catch 块
				e.printStackTrace();
			} catch (InvocationTargetException e)
			{
				// TODO 自动生成 catch 块
				e.printStackTrace();
			}
		}
		return o;
	}

	public static String map2url(Map map)
	{
		Iterator iterMap = map.entrySet().iterator();

		StringBuffer sb = new StringBuffer();
		while (iterMap.hasNext())
		{
			Map.Entry entry = (Map.Entry) iterMap.next();
			sb.append("&"+(String) entry.getKey()+"="+entry.getValue());
		}
		return sb.toString();
	}

	/*
	 * newo可以是Map
	 */
	public static void copyProperties(Object oldo, Object newo)
	{
		try
		{
			PropertyUtils.copyProperties(oldo, newo);
		} catch (IllegalAccessException e)
		{
			e.printStackTrace();
		} catch (InvocationTargetException e)
		{
			e.printStackTrace();
		} catch (NoSuchMethodException e)
		{
			e.printStackTrace();
		}
	}

	public static Object getValue(Object o, String property)
	{
		try
		{
		    if(o instanceof HashMap)
		    {
		        return ((HashMap)o).get(property);
		    }

			return PropertyUtils.getSimpleProperty(o, property);
		} catch (IllegalAccessException e)
		{
			e.printStackTrace();
		} catch (InvocationTargetException e)
		{
			e.printStackTrace();
		} catch (NoSuchMethodException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public static void setValue(Object o, String property, Object value)
    {
        try
        {
            PropertyUtils.setProperty(o, property,value);
        } catch (IllegalAccessException e)
        {
            e.printStackTrace();
        } catch (InvocationTargetException e)
        {
            e.printStackTrace();
        } catch (NoSuchMethodException e)
        {
            e.printStackTrace();
        }
    }

	private static Object convertType(String classType, String value) {
        if (value == null) {
            return null;
        }
        try {
            if (classType.equals("java.lang.String")) {
                return value;
            } else if (classType.equals("java.lang.Integer")) {
                return Integer.valueOf(value);
            } else if (classType.equals("java.lang.Long")) {
                return Long.valueOf(value);
            } else if (classType.equals("java.lang.Float")) {
                return Float.valueOf(value);
            } else if (classType.equals("java.lang.Double")) {
                return Double.valueOf(value);
            } else if (classType.equals("java.math.BigDecimal")) {
                return new BigDecimal(value);
            } else if (classType.equals("java.util.Date")) {
                SimpleDateFormat formatter;
                if (value.length() == 10) {
                    formatter = new SimpleDateFormat("yyyy-MM-dd");
                } else if (value.length() == 16) {
                    formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                } else if (value.length() == 19) {
                    formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                } else {
                    formatter = new SimpleDateFormat("yyyy-MM-dd");
                }
                formatter.setLenient(false);
                return formatter.parse(value);
            } else if (classType.equals("java.sql.Date")) {
                SimpleDateFormat formatter;
                if (value.length() == 10) {
                    formatter = new SimpleDateFormat("yyyy-MM-dd");
                } else if (value.length() == 16) {
                    formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                } else if (value.length() == 19) {
                    formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                } else {
                    formatter = new SimpleDateFormat("yyyy-MM-dd");
                }
                formatter.setLenient(false);
                java.util.Date date = formatter.parse(value);
                return new java.sql.Date(date.getTime());
            } else if (classType.equals("java.lang.Boolean")) {
                return Boolean.valueOf(value);
            } else if (classType.equals("java.lang.Byte")) {
                return Byte.valueOf(value);
            } else if (classType.equals("java.lang.Short")) {
                return Short.valueOf(value);
            } else if (classType.equals("java.lang.Clob")) {
                return new javax.sql.rowset.serial.SerialClob(value
						.toCharArray());
            }else {
                return null;
            }
        } catch (NumberFormatException e) {
            return null;
        } catch (ParseException e) {
            return null;
        } catch (SerialException e) {
        	return null;
		} catch (SQLException e) {
			return null;
		}
    }

	/*
	 * 属性是否可读 bean为对象名，property为bean的属性名，如果属性为对象用.方式访问 exapmle
	 * isReadable(book,"name") isReadable(book,"author.name") return
	 * 没有此属性或不可读、写返回false
	 */
	public static boolean isReadable(Object bean, String property)
	{
		return PropertyUtils.isReadable(bean, property);
	}

	/*
	 * 属性是否可写
	 */
	public static boolean isWriteable(Object bean, String property)
	{
		return PropertyUtils.isWriteable(bean, property);
	}

	public static DynaBean createBean(String beanname, String property[],
                                      String type[])
	{
		DynaProperty[] beanProperties = new DynaProperty[property.length];

		for (int i = 0; i < property.length; i++)
		{
			if (type[i].equals("str"))
			{
				DynaProperty dp = new DynaProperty(property[i], String.class);
				beanProperties[i] = dp;
			}
			else if (type[i].equals("int"))
			{
				DynaProperty dp = new DynaProperty(property[i], Integer.class);
				beanProperties[i] = dp;
			}
			else if (type[i].equals("date"))
			{
				DynaProperty dp = new DynaProperty(property[i],
						java.util.Date.class);
				beanProperties[i] = dp;
			}
			else if (type[i].equals("long"))
			{
				DynaProperty dp = new DynaProperty(property[i], Long.class);
				beanProperties[i] = dp;
			}
			else if (type[i].equals("float"))
			{
				DynaProperty dp = new DynaProperty(property[i], Float.class);
				beanProperties[i] = dp;
			}
		}

		BasicDynaClass personClass = new BasicDynaClass(beanname,
				BasicDynaBean.class, beanProperties);
		// 生成这个bean的一个实例
		DynaBean bean;
		try
		{
			bean = personClass.newInstance();
			return bean;
		} catch (IllegalAccessException e)
		{
			e.printStackTrace();
		} catch (InstantiationException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public static DynaBean createBeanByString(String beanname,
                                              String property[])
	{
		DynaProperty[] beanProperties = new DynaProperty[property.length];

		for (int i = 0; i < property.length; i++)
		{
			DynaProperty dp = new DynaProperty(property[i], String.class);
			beanProperties[i] = dp;
		}

		BasicDynaClass personClass = new BasicDynaClass(beanname,
				BasicDynaBean.class, beanProperties);
		// 生成这个bean的一个实例
		DynaBean bean;
		try
		{
			bean = personClass.newInstance();
			return bean;
		} catch (IllegalAccessException e)
		{
			e.printStackTrace();
		} catch (InstantiationException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public static Object cloneBean(Object o)
	{
		try
		{
			return BeanUtils.cloneBean(o);
		} catch (IllegalAccessException e)
		{
			e.printStackTrace();
		} catch (InstantiationException e)
		{
			e.printStackTrace();
		} catch (InvocationTargetException e)
		{
			e.printStackTrace();
		} catch (NoSuchMethodException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public static Method getColumnMethod(Class cl, String fieldName)
			throws Exception
	{
		Method method = null;
		String fieldName0 = "set";

		try
		{
			Field field = null;
			Field[] fields = cl.getDeclaredFields();

			for (int index = 0; index < fields.length; index++)
			{
				if (fields[index].getName().trim().toLowerCase().equals(
						fieldName.trim().toLowerCase()))
				{
					field = fields[index];
					break;
				}
			}

			if (field == null)
			{
				return null;
			}

			fieldName = field.getName();
			fieldName0 += fieldName.substring(0, 1).toUpperCase() + fieldName
					.substring(1);
			method = cl.getMethod(fieldName0, new Class[]
			{ field.getType() });

		} catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
		return method;
	}

	public static String getField(Class cl)
	{
		// 解析属性信息
		Field[] f = cl.getDeclaredFields();
		for (Field field : f)
		{
			// System.out.println("属性="+field.toString());
			// System.out.println("数据类型＝"+field.getType());
			// System.out.println("属性名＝"+field.getName());
			// int mod=field.getModifiers();
			// System.out.println("属性修饰符＝"+Modifier.toString(mod));
		}
		// 解析方法信息
		Method[] methodlist = cl.getDeclaredMethods();
		for (Method method : methodlist)
		{
			// System.out.println("---------------");
			// System.out.println("方法＝"+method.toString());
			// System.out.println("方法名＝"+method.getName());
			// int mod=method.getModifiers();
			// System.out.println("方法修饰符＝"+Modifier.toString(mod));
			// System.out.println("方法参数列表");
			Class pts[] = method.getParameterTypes();
			for (int i = 0; i < pts.length; i++)
			{
				if (i != 0)
				{
					// System.out.println(class1);
				}
				// System.out.println("返回类型" + method.getReturnType());
			}
		}
		return "";
	}

	public static String getField(Class[] cla, String[] ss)
	{
		List list = new ArrayList();
		for (int a = 0; a < ss.length; a++)
		{
			String allstr = "";

			Class cl = cla[a];

			String s = ss[a];
			Field[] f = cl.getDeclaredFields();
			for (int i = 0; i < f.length; i++)
			{
				Field field = f[i];
				String typename = f[i].getType().getName();

				if (typename.indexOf("java") != -1)
				{
					if (!typename.equals("java.util.List"))
					{
						allstr += s + "." + field.getName() + " as " + s + "_" + field
								.getName() + ",";
					}
				}
			}
			// System.out.println(allstr);

			list.add(allstr);
		}
		return getField(list);
	}

	public static String getField(List list)
	{
		String aaa = "";
		for (int a = 0; a < list.size(); a++)
		{
			aaa += list.get(a).toString();
		}
		return aaa.substring(0, aaa.length() - 1);
	}

	/**
	 * 得到指定类型的属性(比如说得到bean中所有List类型的属性名)
	 *
	 * @param cl
	 * @param typename
	 * @return
	 */
	public static String[] getField(Class cl, String typename)
	{
		String temp = "";
		// 解析属性信息
		Field[] f = cl.getDeclaredFields();
		for (Field field : f)
		{
			if (field.getType().getName().equals(typename))
			{
				temp = field.getName() + ",";
			}
		}
		return temp.split(",");
	}

	public static List listSortTree(List list , String mainkey , String p_property , String has_property) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
	{
		List final_list = new ArrayList();

		List parent_list = new ArrayList();
		List sub_list    = new ArrayList();

		if(list!=null&&list.size()>0)
		{
			//get parent list
			for(int i=0; i<list.size();i++)
			{
				Object bean = (Object)list.get(i);
				String parent_id = PropertyUtils.getSimpleProperty(bean, p_property).toString();
				if(parent_id.equals("0"))
				{
					parent_list.add(bean);
				}
				else
				{
					sub_list.add(bean);
				}
			}

			//digui
			for(int i=0; i<parent_list.size();i++)
			{
				Object bean = (Object)parent_list.get(i);
				subsort(bean,sub_list,final_list,mainkey,p_property,has_property);
			}
		}

		return final_list;
	}

	public static void subsort(Object bean , List allSublist , List final_list , String mainkey , String p_property , String has_property) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
	{
		String cur_parent_id = PropertyUtils.getSimpleProperty(bean, mainkey).toString();

		List cur_sub_list = new ArrayList();

		for(int i=0;i<allSublist.size();i++)
		{
			Object o = (Object)allSublist.get(i);
			String parent_id = PropertyUtils.getSimpleProperty(o, p_property).toString();
			if(cur_parent_id.equals(parent_id))
			{
				cur_sub_list.add(o);
			}
		}

		if(cur_sub_list!=null&&cur_sub_list.size() > 0)
		{
			PropertyUtils.setProperty(bean, has_property, "have");
			final_list.add(bean);
			for(int i=0; i<cur_sub_list.size(); i++)
			{
				Object c = (Object)cur_sub_list.get(i);
				subsort(c , allSublist , final_list , mainkey , p_property , has_property);
			}
		}
		else
		{
			final_list.add(bean);
		}
	}

	public static Object trim(Object obj){
        if(obj!=null){
            if(obj instanceof Map){
                Map tmpMap=(Map)obj;
                if(tmpMap.size()!=0){
                    Set tmpSet=tmpMap.entrySet();
                    Iterator iterator=tmpSet.iterator();
                    while(iterator.hasNext()){
                        String key=(String)iterator.next();
                        Object tmpobj=tmpMap.get(key);
                        tmpMap.remove(key);
                        tmpMap.put(key, trimObject(tmpobj));
                    }
                }
            }else if(obj instanceof List){
                List tmpList=(List)obj;
                if(tmpList.size()!=0){
                    for(int i=0;i<tmpList.size();i++){
                        Object tmpobj=tmpList.get(i);
                        tmpList.set(i, trimObject(tmpobj));
                    }

                }

            }else if(obj instanceof Set){
                Set tmpSet=(Set)obj;
                if(tmpSet.size()!=0){
                    Iterator iterator=tmpSet.iterator();
                    while(iterator.hasNext()){
                        Object tmpobj=iterator.next();
                        tmpSet.remove(tmpobj);
                        tmpSet.add(trimObject(tmpobj));
                    }
                }
            }else{
                return trimObject(obj);
            }
        }
        return null;
    }

	public static Object trimObject(Object obj){
	        if(obj!=null){
	            if(obj instanceof Map){
	                return null;
	            }else if(obj instanceof List){
	                return null;
	            }else if(obj instanceof Set){
	                return null;
	            }else{
	                Class tmpclass=obj.getClass();
	                Field[] tmpfield=tmpclass.getDeclaredFields();
	                for(int i=0;i<tmpfield.length;i++){
	                    Field field = tmpfield[i];

	                    String fieldName = field.getName();
	                    if(fieldName.equals("serialVersionUID"))continue;
	                    String backName = fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
	                    String getMethodName="get"+backName;
	                    String setMethodName="set"+backName;
	                    Method getMethod,setMethod;
	                    try {
	                        getMethod = tmpclass.getMethod(getMethodName,new Class[]{});
	                        Object value = getMethod.invoke(obj, new Object[] {});
	                        if(value==null)continue;
	                        if(value instanceof String){
	                            value= String.valueOf(value).trim();
	                        }

	                        if("java.lang.String".equals(tmpfield[i].getType().getName())){
	                            setMethod=tmpclass.getMethod(setMethodName, new Class[]{field.getType()});
	                            setMethod.invoke(obj, new Object[] {value});
	                        }

	                    } catch (SecurityException e) {
	                        // TODO Auto-generated catch block
	                        //e.printStackTrace();
	                    } catch (NoSuchMethodException e) {
	                        // TODO Auto-generated catch block
	                        //e.printStackTrace();
	                    }catch (IllegalArgumentException e) {
	                        // TODO Auto-generated catch block
	                        //e.printStackTrace();
	                    } catch (IllegalAccessException e) {
	                    } catch (InvocationTargetException e) {
	                    }
	                }
	                return obj;
	            }
	        }
	        return null;
	    }


	/**
     * @param obj bean瀵硅薄
     * @param map request.getParameterMap()
     */
    private static void setBeanProperty(Object obj, Map map){
        if(map==null) return;
        for (Object o : map.entrySet()) {
            Map.Entry entry = (Map.Entry) o;
            String key = (String) entry.getKey();

            String[] values=null;
            String value=null;
            Object object= entry.getValue();
            if(object!=null){
                if(object.getClass()==String[].class) {
                    values = (String[])object;
                    value=values[0];
                }
                else if(object.getClass()==String.class) {
                    values = new String[]{(String)object};
                    value = (String)object;
                }
            }
            //String[] values = (String[]) entry.getValue();
            if(!PropertyUtils.isWriteable(obj,key)) continue;
            try {
                Class cls = PropertyUtils.getPropertyType(obj,key);
                if (cls == null) continue;
                //String value = (values != null && values.length > 0) ? values[0] : null;
                if (cls == String.class) PropertyUtils.setProperty(obj, key, value);
                else if (cls == String[].class) PropertyUtils.setProperty(obj, key, values);
                else if (cls == BigDecimal.class) PropertyUtils.setProperty(obj, key, BeanTools.toBigDecimal(value));
                else if (cls == BigDecimal[].class) PropertyUtils.setProperty(obj, key, BeanTools.toBigDecimal(values));
                else if (cls == BigInteger.class) PropertyUtils.setProperty(obj, key, BeanTools.toBigInteger(value));
                else if (cls == BigInteger[].class) PropertyUtils.setProperty(obj, key, BeanTools.toBigInteger(values));
                else if (cls == Boolean.class) PropertyUtils.setProperty(obj, key, BeanTools.toBoolean(value));
                else if (cls == Boolean[].class) PropertyUtils.setProperty(obj, key, BeanTools.toBoolean(values));
                else if (cls == Double.class) PropertyUtils.setProperty(obj, key, BeanTools.toDouble(value));
                else if (cls == Double[].class) PropertyUtils.setProperty(obj, key, BeanTools.toDouble(values));
                else if (cls == Float.class) PropertyUtils.setProperty(obj, key, BeanTools.toFloat(value));
                else if (cls == Float[].class) PropertyUtils.setProperty(obj, key, BeanTools.toFloat(values));
                else if (cls == Integer.class) PropertyUtils.setProperty(obj, key, BeanTools.toInteger(value));
                else if (cls == Integer[].class) PropertyUtils.setProperty(obj, key, BeanTools.toInteger(values));
                else if (cls == Long.class) PropertyUtils.setProperty(obj, key, BeanTools.toLong(value));
                else if (cls == Long[].class) PropertyUtils.setProperty(obj, key, BeanTools.toLong(values));
                else if (cls == Short.class) PropertyUtils.setProperty(obj, key, BeanTools.toShort(value));
                else if (cls == Short[].class) PropertyUtils.setProperty(obj, key, BeanTools.toShort(values));
                else if (cls == Byte.class) PropertyUtils.setProperty(obj, key, BeanTools.toByte(value));
                else if (cls == Byte[].class) PropertyUtils.setProperty(obj, key, BeanTools.toByte(values));
                else if (cls == Date.class) PropertyUtils.setProperty(obj, key, BeanTools.toDate(value));
                else if (cls == Date[].class) PropertyUtils.setProperty(obj, key, BeanTools.toDate(values));
            }
            catch (Exception e) {
               e.printStackTrace();
            }
        }
    }

    /**
     * 瀛楃涓茶浆鎹� BigDecimal
     *
     * @param value 瀛楃涓�
     * @return BigDecimal
     */
    public static BigDecimal toBigDecimal(String value) {
        if (value == null || value.equals("") || value.equals("null")) return null;
        try {
            return new BigDecimal(value);
        }
        catch (Exception e) {
            logger.error(getExceptionMessage(e));
            return null;
        }
    }


    /**
     * 瀛楃涓叉暟缁勮浆鎹� BigDecimal[]
     *
     * @param values 瀛楃涓叉暟缁�
     * @return BigDecimal[]
     */
    public static BigDecimal[] toBigDecimal(String[] values) {
        BigDecimal[] result = new BigDecimal[values.length];
        for (int i = 0; i < values.length; i++) result[i] = toBigDecimal(values[i]);
        return result;
    }


    /**
     * 瀛楃涓茶浆鎹� BigInteger
     *
     * @param value 瀛楃涓�
     * @return BigInteger
     */
    public static BigInteger toBigInteger(String value) {
        if (value == null || value.equals("") || value.equals("null")) return null;
        try {
            return new BigInteger(value);
        }
        catch (Exception e) {
            logger.error(getExceptionMessage(e));
            return null;
        }
    }


    /**
     * 瀛楃涓叉暟缁勮浆鎹� BigInteger[]
     *
     * @param values 瀛楃涓叉暟缁�
     * @return BigInteger[]
     */
    public static BigInteger[] toBigInteger(String[] values) {
        BigInteger[] result = new BigInteger[values.length];
        for (int i = 0; i < values.length; i++) result[i] = toBigInteger(values[i]);
        return result;
    }


    /**
     * 瀛楃涓茶浆鎹� Boolean
     *
     * @param value 瀛楃涓�
     * @return Boolean
     */
    public static Boolean toBoolean(String value) {
        if (value == null || value.equals("") || value.equals("null")) return null;
        try {
            return Boolean.parseBoolean(value);
        }
        catch (Exception e) {
            logger.error(getExceptionMessage(e));
            return null;
        }
    }


    /**
     * 瀛楃涓叉暟缁勮浆鎹� Boolean[]
     *
     * @param values 瀛楃涓叉暟缁�
     * @return Boolean[]
     */
    public static Boolean[] toBoolean(String[] values) {
        Boolean[] result = new Boolean[values.length];
        for (int i = 0; i < values.length; i++) result[i] = toBoolean(values[i]);
        return result;
    }

    /**
     * 瀛楃涓茶浆鎹� Double
     *
     * @param value 瀛楃涓�
     * @return Double
     */
    public static Double toDouble(String value) {
        if (value == null || value.equals("") || value.equals("null")) return null;
        try {
            return Double.parseDouble(value);
        }
        catch (Exception e) {
            logger.error(getExceptionMessage(e));
            return null;
        }
    }

    /**
     * 瀛楃涓叉暟缁勮浆鎹� Double[]
     *
     * @param values 瀛楃涓叉暟缁�
     * @return Double[]
     */
    public static Double[] toDouble(String[] values) {
        Double[] result = new Double[values.length];
        for (int i = 0; i < values.length; i++) result[i] = toDouble(values[i]);
        return result;
    }

    /**
     * 瀛楃涓茶浆鎹� Float
     *
     * @param value 瀛楃涓�
     * @return Float
     */
    public static Float toFloat(String value) {
        if (value == null || value.equals("") || value.equals("null")) return null;
        try {
            return Float.parseFloat(value);
        }
        catch (Exception e) {
            logger.error(getExceptionMessage(e));
            return null;
        }
    }

    /**
     * 瀛楃涓叉暟缁勮浆鎹� Float[]
     *
     * @param values 瀛楃涓叉暟缁�
     * @return Float[]
     */
    public static Float[] toFloat(String[] values) {
        Float[] result = new Float[values.length];
        for (int i = 0; i < values.length; i++) result[i] = toFloat(values[i]);
        return result;
    }


    /**
     * 瀛楃涓茶浆鎹� Integer
     *
     * @param value 瀛楃涓�
     * @return Integer
     */
    public static Integer toInteger(String value) {
        if (value == null || value.equals("") || value.equals("null")) return null;
        try {
            return Integer.parseInt(value);
        }
        catch (Exception e) {
            logger.error(getExceptionMessage(e));
            return null;
        }
    }

    /**
     * 瀛楃涓叉暟缁勮浆鎹� Integer[]
     *
     * @param values 瀛楃涓�
     * @return Integer[]
     */
    public static Integer[] toInteger(String[] values) {
        Integer[] result = new Integer[values.length];
        for (int i = 0; i < values.length; i++) result[i] = toInteger(values[i]);
        return result;
    }

    /**
     * 瀛楃涓茶浆鎹� Long
     *
     * @param value 瀛楃涓�
     * @return Long
     */
    public static Long toLong(String value) {
        if (value == null || value.equals("") || value.equals("null")) return null;
        try {
            return Long.parseLong(value);
        }
        catch (Exception e) {
            logger.error(getExceptionMessage(e));
            return null;
        }
    }

    /**
     * 瀛楃涓叉暟缁勮浆鎹� Long[]
     *
     * @param values 瀛楃涓�
     * @return Long[]
     */
    public static Long[] toLong(String[] values) {
        Long[] result = new Long[values.length];
        for (int i = 0; i < values.length; i++) result[i] = toLong(values[i]);
        return result;
    }


    /**
     * 瀛楃涓茶浆鎹� Short
     *
     * @param value 瀛楃涓�
     * @return Short
     */
    public static Short toShort(String value) {
        if (value == null || value.equals("") || value.equals("null")) return null;
        try {
            return Short.parseShort(value);
        }
        catch (Exception e) {
            logger.error(getExceptionMessage(e));
            return null;
        }
    }

    /**
     * 瀛楃涓叉暟缁勮浆鎹� Short[]
     *
     * @param values 瀛楃涓�
     * @return Short[]
     */
    public static Short[] toShort(String[] values) {
        Short[] result = new Short[values.length];
        for (int i = 0; i < values.length; i++) result[i] = toShort(values[i]);
        return result;
    }


    public static Byte toByte(String value) {
        if (value == null || value.equals("") || value.equals("null")) return null;
        try {
            return Byte.parseByte(value);
        }
        catch (Exception e) {
            logger.error(getExceptionMessage(e));
            return null;
        }
    }

    public static Byte[] toByte(String[] values) {
        Byte[] result = new Byte[values.length];
        for (int i = 0; i < values.length; i++) result[i] = toByte(values[i]);
        return result;
    }


    /**
     * 瀛楃涓茶浆鎹� Date
     *
     * @param value 瀛楃涓�
     * @return Date
     */
    public static Date toDate(String value) {
        if (value == null || value.equals("") || value.equals("null")) return null;
        try {
            //DateFormat dateFormat = new DateFormat();
            dateFormat.setLenient(false);
            return dateFormat.parse(value);
        }
        catch (Exception e) {
            logger.error(getExceptionMessage(e));
            return null;
        }
    }

    /**
     * 瀛楃涓叉暟缁勮浆鎹� Date[]
     *
     * @param values 瀛楃涓�
     * @return Date[]
     */
    public static Date[] toDate(String[] values) {
        Date[] result = new Date[values.length];
        for (int i = 0; i < values.length; i++) result[i] = toDate(values[i]);
        return result;
    }

    private static String getExceptionMessage(Exception e) {
        String msg = e.getMessage();
        if (msg == null) msg = e.getClass().getName();
        return msg;
    }

    public static Object copyAdd(Object source, Object add) throws Exception
    {
        Class<?> add_classType = add.getClass();
        Class<?> source_classType = source.getClass();
        //获得对象的所有成员变量
        Field[] fields = source_classType.getDeclaredFields();
        Field[] fields_add = add_classType.getDeclaredFields();
        for(Field field : fields)
        {
            //获取成员变量的名字
            String name = field.getName();    //获取成员变量的名字，此处为id，name,age
            //System.out.println(name);

            //获取get和set方法的名字
            String firstLetter = name.substring(0,1).toUpperCase();    //将属性的首字母转换为大写
            String getMethodName = "get" + firstLetter + name.substring(1);
            String setMethodName = "set" + firstLetter + name.substring(1);
            //System.out.println(getMethodName + "," + setMethodName);

            //获取方法对象
            Method getMethod = source_classType.getMethod(getMethodName, new Class[]{});
            Method setMethod = source_classType.getMethod(setMethodName, new Class[]{field.getType()});//注意set方法需要传入参数类型

            for(Field field2 : fields_add)
            {
                String name2 = field2.getName();
                if(name.equals(name2)){
                    System.out.println(name+"="+name2);
                  //调用get方法获取旧的对象的值
                    Object value = getMethod.invoke(source, new Object[]{});
                    //调用set方法将这个值复制到新的对象中去
                    if(value==null){
                        String firstLetter2 = name2.substring(0,1).toUpperCase();    //将属性的首字母转换为大写
                        String getMethodName2 = "get" + firstLetter2 + name2.substring(1);
                        //System.out.println(getMethodName + "," + setMethodName);
                        //获取方法对象
                        Method add_getMethod = add_classType.getMethod(getMethodName2, new Class[]{});
                        Object add_value = add_getMethod.invoke(add, new Object[]{});
                        if(add_value!=null)
                            setMethod.invoke(source, new Object[]{add_value});
                    }
                    break;
                }
            }
        }
        return source;
    }

    public static List bean2list(Object bean) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException
    {
        HashMap map = new HashMap();
        List list = new ArrayList();
        Field[] field = bean.getClass().getDeclaredFields();
        for (int i = 0; i < field.length; i++)
        {
            String fieldname = field[i].getName();
            String firstLetter = fieldname.substring(0,1).toUpperCase();    //将属性的首字母转换为大写
            String getMethodName = "get" + firstLetter + fieldname.substring(1);
            //获取方法对象
            Method getMethod = bean.getClass().getMethod(getMethodName, new Class[]{});
            Object value = getMethod.invoke(bean, new Object[] {});
            map.put("field_name", fieldname);
            map.put("field_value", value);
            list.add(map);
        }
        return list;
    }


    public static <T> T wrapPageBean(Class<T> cls, Map map) {
        try {
            T pageInfo = cls.newInstance();
            setBeanProperty(pageInfo, map);
            return pageInfo;
        }
        catch (Exception e) {
            logger.error(getExceptionMessage(e));
            return null;
        }
    }

    /**
     * 集合复制到集合
     *
     * @param source           源list数据
     * @param destinationClass 目标list数据类型class
     * @param <E>
     * @return
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws InstantiationException
     */
    public static <E> List<E> copyListToList(List<?> source, Class<E> destinationClass) {
        if (source.size() == 0) return Collections.emptyList();
        List<E> res = new ArrayList<E>(source.size());
        for (Object o : source) {
            E e = null;
            try {
                e = destinationClass.newInstance();
            } catch (InstantiationException ex) {
                ex.printStackTrace();
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
            }
            org.springframework.beans.BeanUtils.copyProperties(o, e);
            res.add(e);
        }
        return res;
    }

	public static Map<String, Object> objectToMap(Object obj) throws Exception {
		if(obj == null){
			return null;
		}

		Map<String, Object> map = new HashMap<String, Object>();

		Field[] declaredFields = obj.getClass().getDeclaredFields();
		for (Field field : declaredFields) {
			field.setAccessible(true);
			map.put(field.getName(), field.get(obj));
		}

		return map;
	}


	//判断该对象是否
	public static boolean isAllFieldNull(Object obj) throws IllegalAccessException {
		Class stuCla = (Class) obj.getClass();// 得到类对象
		Field[] fs = stuCla.getDeclaredFields();//得到属性集合
		boolean flag = true;
		for (Field f : fs) {//遍历属性
			f.setAccessible(true); // 设置属性是可以访问的(私有的也可以)
			Object val = f.get(obj);// 得到此属性的值
			if(val!=null && (val+"").length()>0 ) {//只要有1个属性不为空,那么就不是所有的属性值都为空
				flag = false;
				break;
			}
		}
		return flag;
	}


	public static void main(String[] args)
    {

    }
}
